package com.dai.wechat.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

public class ApiUtil {

    private final static String rainbowUrl = "http://api.tianapi.com/caihongpi/index?key=";
    private final static String englishUrl = "http://api.tianapi.com/everyday/index?key=";
    private final static String weather = "http://wthrcdn.etouch.cn/weather_mini?";
    private final static String RHESIS_URL = "http://api.tianapi.com/mingyan/index?key=";
    private final static String key = "15b1b6cbb8473338bb2f400c582a666e";
    // 天气情况查询接口地址
    private final static String API_URL = "http://apis.juhe.cn/simpleWeather/query?";
    // 接口请求Key
    private final static String API_KEY = "730a1caa240245c9efb39ac048073681";
    private final static String rainbowWord = "阳光落在屋里，爱你藏在心里";
    private final static String english = "People always prepare for the worst but hope for the best. 人们总是做好了最坏的打算但仍期望着最美好的结局。";


    public static String getRainbow(){

        //java环境中文传值时，需特别注意字符编码问题

        String jsonResult = request(rainbowUrl, key);
        // 获得json字符串
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        if (jsonObject.getIntValue("code") == 200) {
            String str = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("content");
            return str;
        }
        // 返回默认语句
        return rainbowWord;

    }

    public static String getEnglish(){

        String jsonResult = request(englishUrl, key);
        // 获得json字符串
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        StringBuilder stringBuilder = new StringBuilder();

        if (jsonObject.getIntValue("code") == 200) {
            String str = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("content");
            String note = jsonObject.getJSONArray("newslist").getJSONObject(0).getString("note");
            stringBuilder.append(str);
            stringBuilder.append("\n");
            stringBuilder.append(note);
            return stringBuilder.toString();
        }
        // 返回默认语句
        return english;
    }

    public static List<String> getWeather(String city){

        Map<String,String> map = new HashMap<>();
        map.put("key",API_KEY);
        map.put("city",city);
        String request = request(API_URL, map);

        // 获得json字符串
        List<String> list = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(request);
        if ("查询成功!".equals(jsonObject.getString("reason"))) {

            JSONObject obj = jsonObject.getJSONObject("result").getJSONArray("future").getJSONObject(0);
            // 获取今日日期
            String date = obj.getString("date");
            list.add(date);
            // 获取今日最高温度以及最低温度
            String temperature = obj.getString("temperature");
            String[] split = temperature.substring(0, temperature.length() - 1).split("/",3);
            for (String s : split) {
                list.add(s);
            }
            // 获取今日天气状况
            String weather = obj.getString("weather");
            list.add(weather);
        }else{
            list.add("数据错误");
        }
        return list;

    }

    public static List<String> getRhesis(){

        List<String> list = new ArrayList<>(2);
        // 经典台词

        String jsonResult = request(RHESIS_URL, key);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        if("success".equals(jsonObject.getString("msg"))){
            //System.out.println(jsonObject);
            JSONObject newslist = jsonObject.getJSONArray("newslist").getJSONObject(0);
            String content = newslist.getString("content");
            String author = newslist.getString("author");
            list.add(content);
            list.add(author);

        }

        return list;
    }

    public static HashMap<String,String> getConstellation(){
        // 星座运势
        String httpUrl = "http://api.tianapi.com/star/index?astro=水瓶座&key=";
        String key = "15b1b6cbb8473338bb2f400c582a666e";
        String jsonResult = request(httpUrl, key);
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        if("success".equals(jsonObject.getString("msg"))){
            //System.out.println(jsonObject);
            List<?> newslist = jsonObject.getJSONArray("newslist");
            HashMap<String,String> map = new HashMap<>();
            for (Object o : newslist) {
                JSONObject json = (JSONObject) o;
                String type = json.getString("type");
                String content = json.getString("content");
                map.put(type,content);

            }
            return map;
        }
        return null;

    }





    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl  + httpArg;
        try {
            // 根据Url创建出对象
            URL url = new URL(httpUrl);
            // 获取连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 发送请求，获取响应输入流
            InputStream is = connection.getInputStream();
            // 通过包装类获取流中信息
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

   /* // 获取天气预报
    public static JSONObject getWeather1(String city) {
        String url = weather;
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("city", city));
        String param = URLEncodedUtils.format(params, "utf-8");
        HttpGet httpGet = new HttpGet(url + param);
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            String result = getJsonStringFromGZIP(httpResponse);// 获取到解压缩之后的字符串
            //System.out.println(result);
            JSONObject obj =JSONObject.parseObject(result);
            if (obj != null && obj.getString("desc").equals("OK")) {

                JSONObject jsonObject = obj.getJSONObject("data").getJSONArray("forecast").getJSONObject(0);
                if(jsonObject != null) return jsonObject;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    private static String getJsonStringFromGZIP(HttpResponse response) {
        String jsonString = null;
        try {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            if (result != -1 && headerData == 0x1f8b) {
                is = new GZIPInputStream(bis);
            } else {
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }
*/

    public static String request(String httpUrl, Map<String,String> map) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        String urlencode = urlencode(map);
        httpUrl += urlencode;

        try {
            // 根据Url创建出对象
            URL url = new URL(httpUrl);
            // 获取连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 发送请求，获取响应输入流
            InputStream is = connection.getInputStream();
            // 通过包装类获取流中信息
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }

    public static String dateToWeek(String datetime) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }


}

